<!--
 * @Descripttion: 
 * @Author: Kevin
 * @Date: 2022-06-14 10:58:57
 * @LastEditors: Tommy Chen
 * @LastEditTime: 2024-07-16
-->
<template>
  <RjModal
    width="600px"
    :title="modalTitle"
    :visible="isVisible"
    @ok="onOk"
    :confirmLoading="confirmLoading"
    @cancel="onCancel"
  >
    <a-form-model
      :labelCol="{ span: 10 }"
      :wrapperCol="{ span: 14 }"
      labelAlign="left"
      :model="macForm"
      ref="macFormRef"
      :rules="ruleObj"
      :colon="false"
    >
      <a-form-model-item
        class="flex col-top"
        prop="mac"
        :label="$t('authMac.mac')"
      >
        <a-input v-model="macForm.mac" :placeholder="$t('authMac.enterTip')" />
      </a-form-model-item>

      <a-form-model-item
        class="flex col-top"
        prop="remark"
        :label="$t('authMac.remark')"
      >
        <a-input v-model="macForm.remark" />
      </a-form-model-item>

      <a-form-model-item
        :label="$t('localAccount.authPolicy')"
        prop="profileId"
      >
        <a-select
          :filterOption="filterOption"
          showSearch
          v-model="macForm.profileId"
          :options="groupOptions"
        >
          <div slot="dropdownRender" slot-scope="menu">
            <v-nodes :vnodes="menu" />
            <a
              style="padding: 4px 8px 8px; cursor: pointer; display: block"
              @mousedown="(e) => e.preventDefault()"
              @click="onAddAuthPolicy"
            >
              <icon-font type="ic-plus" />
              {{ $t('localAccount.addAuthPlicy2') }}
            </a>
          </div>
        </a-select>
      </a-form-model-item>
    </a-form-model>
  </RjModal>
</template>

<script>
import { requestHttp, maccApi } from '@utils/index';
import { mapState } from 'vuex';
import { getByteLength } from '@/utils';
import { ValiDateTools } from '@/utils';
import authSysMixin from '@project/authSys/mixin/authSysMixin';
import _ from 'lodash';
export default {
  name: 'addMacModal',
  mixins: [authSysMixin],
  components: {
    VNodes: {
      functional: true,
      render: (h, ctx) => ctx.props.vnodes,
    },
  },
  model: {
    prop: 'value',
    event: 'set',
  },
  data() {
    const validateRemark = (rule, val, cb) => {
      if (!val) {
        cb();
      }

      if (getByteLength(val) > 128) {
        cb(new Error(this.$t('common.byteRange', [128])));
      } else {
        cb();
      }
    };
    const ruleObj = {
      mac: [
        {
          required: true,
          trigger: 'blur',
          message: this.$t('userManage.fieldIsRquired'),
        },
        {
          trigger: 'blur',
          validator: (rule, value, callback) => {
            const { result, msg } = ValiDateTools.checkMac(value);
            if (!result) {
              return callback(new Error(msg));
            }

            callback();
          },
        },
      ],
      remark: [
        {
          trigger: 'blur',
          validator: validateRemark,
        },
      ],
    };
    return {
      ruleObj,
      macForm: {
        mac: '',
        remark: '',
        profileId: '',
      },
      confirmLoading: false,
      addModalShow: false,
      isVisible: false,
    };
  },
  watch: {
    value(val) {
      // val && this.getGroup();
    },
  },
  computed: {
    ...mapState('AuthCommon', ['authPolicys']),
    modalTitle() {
      return this.macForm.id ? this.$t('authMac.edit') : this.$t('authMac.add');
    },
    groupOptions() {
      return this.authPolicys.map(
        (item) =>
          (item = {
            ...item,
            ...{ label: item.name, value: item.uuid },
          })
      );
    },
  },
  methods: {
    setAuthPolicyId(policyId) {
      this.macForm.profileId = policyId;
    },
    onAddAuthPolicy() {
      this.$emit('addAuthPolicy');
    },
    /**
     * @description: 过滤用户组
     * @param {*} input
     * @param {*} option
     * @return {*}
     */
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
    openModal(record) {
      this.isVisible = true;
      if (record) {
        this.macForm = _.cloneDeep(record);
      }
    },
    quantityInput(e) {
      let { value } = e.target;
      this.macForm.quantity = value.replace(/\D/g, '');
    },
    onOk() {
      this.$refs.macFormRef.validate((valid) => {
        if (valid) {
          if (this.macForm.id) {
            this.saveMac({ operation: 'edit' });
          } else {
            this.saveMac();
          }
        }
      });
    },
    change(e) {
      if (e == 'custom') {
        this.macForm.userGroupId = '';
        this.addModalShow = true;
      }
    },
    async saveMac(paramObj = { operation: 'add' }) {
      let url = '';
      let successTxt = '';
      let method = '';
      if (paramObj.operation === 'add') {
        url = maccApi.MACC_AUTH_MAC_ADD_POST_API;
        successTxt = this.$t('common.addSuceess');
        method = 'POST';
      } else {
        url = maccApi.MACC_AUTH_MAC_UPDATE_PUT_API;
        successTxt = this.$t('common.editSuccess');
        method = 'PUT';
      }

      const params = this.macForm;
      params.groupId = this.groupId;
      let res = await this.requestHttpAuth({
        api: url,
        method,
        params,
      });

      this.confirmLoading = false;

      // tommy 240715 临时规避
      if (res.data?.success == false) {
        res.data.code = -1;
        res.data.msg = res.data.message;
      }

      if (res.data.code === 0) {
        this.$message.success(successTxt);
        this.$emit('refreshList');
        this.onCancel();
      } else {
        this.$message.warning(res.data.msg);
      }
    },
    resetForm() {
      this.macForm = {
        mac: '',
        remark: '',
        profileId: '',
      };
    },
    onCancel() {
      this.resetForm();
      this.isVisible = false;
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.ant-form-item {
  margin-bottom: 8px;
}
.expand-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #000000e5;
  cursor: pointer;
  margin-bottom: 16px;
  font-weight: 500;
  i {
    margin-top: 3px;
    font-size: 18px;
  }
}
.flex {
  display: flex !important;
  flex-direction: row !important;
  align-items: center;
}
.col-top {
  align-items: flex-start !important;
}
.mb-16 {
  margin-bottom: 16px;
}
</style>
